package com.example.teach.service.impl;

import ch.qos.logback.core.util.StringUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.teach.entity.Article;
import com.example.teach.entity.Result;
import com.example.teach.entity.User;
import com.example.teach.entity.UserLikeArticle;
import com.example.teach.mapper.ArticleMapper;
import com.example.teach.mapper.CategoryMapper;
import com.example.teach.mapper.UserLikeArticleMapper;
import com.example.teach.mapper.UserMapper;
import com.example.teach.service.ArticleService;
import com.example.teach.vo.ArticlePageVO;
import com.example.teach.vo.ArticleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private UserLikeArticleMapper userLikeArticleMapper;



    @Override
    public Result add(ArticleVO articleVO) {
        Article article = new Article();
        BeanUtils.copyProperties(articleVO,article);
        article.setCreatedTime(LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES));
        article.setUpdatedTime(LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES));
        articleMapper.insert(article);
        return Result.success(article);
    }

    @Override
    public Result articlePage(Integer pageNum, Integer pageSize, String str) {

        if(StringUtil.isNullOrEmpty(str)){  // 分页返回所有结果
            List<Article> articles = articleMapper.selectList(new QueryWrapper<Article>().orderByAsc("id"));
            List<ArticlePageVO> articlePageVOS = new ArrayList<>();
            for (Article article : articles) {
                ArticlePageVO articlePageVO = new ArticlePageVO();
                articlePageVO.setId(article.getId());
                articlePageVO.setTitle(article.getTitle());
                articlePageVO.setContent(article.getContent());
                articlePageVO.setUserName(userMapper.selectuserNameByUserId(article.getUserId()));
                articlePageVO.setCategoryName(categoryMapper.selectById(article.getCategoryId()).getName());
                articlePageVO.setViewCount(article.getViewCount());
                articlePageVO.setLikeCount(article.getLikeCount());
                articlePageVO.setCommentCount(article.getCommentCount());
                articlePageVO.setCreateTime(article.getCreatedTime());
                articlePageVO.setUpdateTime(article.getUpdatedTime());
                articlePageVOS.add(articlePageVO);
            }
            Page<ArticlePageVO> result = new Page<>();
            result.setRecords(articlePageVOS);
            result.setTotal(articlePageVOS.size());
            return Result.success(result);
        }

        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.like("title",str);
        List<Article> articleList = articleMapper.selectList(articleQueryWrapper);

        if(!articleList.isEmpty()){ //按标题查
            List<ArticlePageVO> articlePageVOS = new ArrayList<>();
            for (Article article : articleList) {
                ArticlePageVO articlePageVO = new ArticlePageVO();
                articlePageVO.setId(article.getId());
                articlePageVO.setTitle(article.getTitle());
                articlePageVO.setContent(article.getContent());
                articlePageVO.setUserName(userMapper.selectuserNameByUserId(article.getUserId()));
                articlePageVO.setCategoryName(categoryMapper.selectById(article.getCategoryId()).getName());
                articlePageVO.setViewCount(article.getViewCount());
                articlePageVO.setLikeCount(article.getLikeCount());
                articlePageVO.setCommentCount(article.getCommentCount());
                articlePageVO.setCreateTime(article.getCreatedTime());
                articlePageVO.setUpdateTime(article.getUpdatedTime());
                articlePageVOS.add(articlePageVO);
            }
            Page<ArticlePageVO> result = new Page<>();
            result.setRecords(articlePageVOS);
            result.setTotal(articlePageVOS.size());
            return Result.success(result);
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("user_name",str);
        User user = userMapper.selectOne(userQueryWrapper);

        if(user != null){     //按人名查
            List<Article> articles = articleMapper.selectList(new QueryWrapper<Article>().eq("user_id",user.getId()));
            List<ArticlePageVO> articlePageVOS = new ArrayList<>();
            for (Article article : articles) {
                ArticlePageVO articlePageVO = new ArticlePageVO();
                articlePageVO.setId(article.getId());
                articlePageVO.setTitle(article.getTitle());
                articlePageVO.setContent(article.getContent());
                articlePageVO.setUserName(userMapper.selectuserNameByUserId(article.getUserId()));
                articlePageVO.setCategoryName(categoryMapper.selectById(article.getCategoryId()).getName());
                articlePageVO.setViewCount(article.getViewCount());
                articlePageVO.setLikeCount(article.getLikeCount());
                articlePageVO.setCommentCount(article.getCommentCount());
                articlePageVO.setCreateTime(article.getCreatedTime());
                articlePageVO.setUpdateTime(article.getUpdatedTime());
                articlePageVOS.add(articlePageVO);
            }
            Page<ArticlePageVO> result = new Page<>();
            result.setRecords(articlePageVOS);
            result.setTotal(articlePageVOS.size());
            return Result.success(result);
        }

        if((user == null && articleList.isEmpty()) && str != null){
            return Result.success("请按照文章标题或作者搜索");
        }


        return Result.error("出错了");
    }

    @Override
    public void addOne(Integer id) {
        articleMapper.add(id);
    }

    @Override
    public Result like(Integer userId, Integer articleId) {
        UserLikeArticle exits = userLikeArticleMapper.selectByUserAndArticle(userId,articleId);
        if(exits != null && exits.getIsLike() == 1){    //取消点赞
            userLikeArticleMapper.deleteById(exits.getId());
            articleMapper.subtractLike(articleId);
            return Result.success("已取消点赞");
        }
        UserLikeArticle like = new UserLikeArticle();
        like.setUserId(userId);
        like.setArticleId(articleId);
        like.setIsLike(1);
        userLikeArticleMapper.insert(like);
        articleMapper.addLike(articleId);
        return Result.success("点赞成功");
    }

    @Override
    public Result pageByCategery(Integer pageNum, Integer pageSize, Integer categoryId) {
        List<Article> articles = articleMapper.selectList(new QueryWrapper<Article>().eq("category_id",categoryId));
        List<ArticlePageVO> articlePageVOS = new ArrayList<>();
        for (Article article : articles) {
            ArticlePageVO articlePageVO = new ArticlePageVO();
            articlePageVO.setId(article.getId());
            articlePageVO.setTitle(article.getTitle());
            articlePageVO.setContent(article.getContent());
            articlePageVO.setUserName(userMapper.selectuserNameByUserId(article.getUserId()));
            articlePageVO.setCategoryName(categoryMapper.selectById(article.getCategoryId()).getName());
            articlePageVO.setViewCount(article.getViewCount());
            articlePageVO.setLikeCount(article.getLikeCount());
            articlePageVO.setCommentCount(article.getCommentCount());
            articlePageVO.setCreateTime(article.getCreatedTime());
            articlePageVO.setUpdateTime(article.getUpdatedTime());
            articlePageVOS.add(articlePageVO);
        }
        Page<ArticlePageVO> result = new Page<>();
        result.setRecords(articlePageVOS);
        result.setTotal(articlePageVOS.size());
        return Result.success(result);

    }


}
